package cn.wolfcode.shop.service.impl;
import java.util.Date;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import cn.wolfcode.shop.domain.UserInfo;
import cn.wolfcode.shop.domain.UserLogin;
import cn.wolfcode.shop.exception.CodeMsg;
import cn.wolfcode.shop.exception.UserException;
import cn.wolfcode.shop.mapper.UserInfoMapper;
import cn.wolfcode.shop.mapper.UserLoginMapper;
import cn.wolfcode.shop.service.IUserLoginService;
import cn.wolfcode.shop.util.MD5;
import cn.wolfcode.shop.util.RedisConstants;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

@Service
@Transactional
public class UserLoginServiceImpl implements IUserLoginService {

    @Autowired
    private UserLoginMapper userLoginMapper;
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void userRegist(String username, String password) throws UserException {
        //基本参数的格式合法校验（忽略）
        if(!StringUtils.hasLength(username)){
            throw new UserException(CodeMsg.USER_NAME_DISABLED);//用户名为空
        }
        //用户名存在与否的校验
        UserLogin userLogin=userLoginMapper.selectByUsername(username);
        if(userLogin!=null){
            throw new UserException(CodeMsg.USER_NAME_EXISTS);//用户名已存在
        }
        UserLogin u=new UserLogin();
        u.setUserName(username);
        u.setPassword(MD5.encode(password));
        u.setState(UserLogin.USER_STATE_NORMAL);
        userLoginMapper.insert(u);
        UserInfo userInfo=new UserInfo();
        userInfo.setRegistTime(new Date());
        userInfo.setId(u.getId());
        userInfoMapper.insert(userInfo);
    }

    @Override
    public String userLogin(String username, String password) throws UserException {
        UserLogin userLogin=userLoginMapper.selectByUsernameAndPassword(username,MD5.encode(password));
        if(userLogin==null){
            throw new UserException(CodeMsg.USER_NAME_OR_PASSWORD_ERROR);
        }
        //生成token,并将用户信息存放到redis中
        String token=UUID.randomUUID().toString();
        String currentUserKey=RedisConstants.CURRENT_USER.replace("TOKEN",token);
        redisTemplate.opsForValue().set(currentUserKey,userLogin);
        //设置token超时(一个月超时)
        redisTemplate.expire(currentUserKey,30, TimeUnit.DAYS);
        return token;
    }

    @Override
    public void logout(String token)throws UserException{
        String currentUserKey=RedisConstants.CURRENT_USER.replace("TOKEN",token);
        Object currentUser = redisTemplate.opsForValue().get(currentUserKey);
        if(currentUser==null){//登录超时
            throw new UserException(CodeMsg.USER_TIME_OUT);
        }
        //删除用于信息（redis）
        redisTemplate.delete(currentUserKey);
    }


}
